//
//  KLFecthMoneyViewController.m
//  KunLun
//
//  Created by Mac on 2018/1/18.
//  Copyright © 2018年 stoneobs@icloud.com. All rights reserved.
//

#import "KLFecthMoneyViewController.h"
#import "STBankModel.h"
#import "STAddCardViewController.h"
#import "STDealRecordController.h"
@interface KLFecthMoneyViewController ()
@property(nonatomic, strong) STButton                     *cardButton;
@property(nonatomic, strong) STButton                     *typeButton;
@property(nonatomic, strong) UITextField                     *moneyTextFiled;
@property(nonatomic, strong) NSMutableArray                     *dataSouce;
@property(nonatomic, strong) STBankModel                     *model;
@end

@implementation KLFecthMoneyViewController


#pragma mark --vc 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"提现";
    [self configSubView];
    [self st_setRightItemWithTitle:@"提现记录" titleColor:[UIColor whiteColor]];
    [self configFooterView];
    [self sendfetchBanksRequest];
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self sendfetchBanksRequest];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
- (void)st_rightBarAction:(id)sender{
    [self.navigationController pushViewController:[STDealRecordController new] animated:YES];
}
#pragma mark --subView
- (void)configSubView{
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 60)];
    header.backgroundColor = [UIColor whiteColor];
    
    UIView * topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 80)];
    topView.backgroundColor = KL_BlueBackGroundColor;
    [header addSubview:topView];
    
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(15, 30, UIScreenWidth - 30, 30)
                                                     text:[NSString stringWithFormat:@"可提现余额￥%@元",self.money]
                                                textColor:FlatWhite
                                                     font:16
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentCenter];
    titleLable.attributedText = [titleLable.text st_convertAttributeStringWithKeyWord:self.money attributes:@{NSForegroundColorAttributeName:KL_redColor}];
    [topView addSubview:titleLable];
    
    STLabel * quMoneyLable = [[STLabel alloc] initWithFrame:CGRectMake(15, titleLable.bottom, UIScreenWidth - 30, 30)
                                                     text:[NSString stringWithFormat:@"可提现渠道商余额￥%@元",
                                                           self.qumoney]
                                                textColor:FlatWhite
                                                     font:16
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentCenter];
    quMoneyLable.attributedText = [quMoneyLable.text st_convertAttributeStringWithKeyWord:self.qumoney attributes:@{NSForegroundColorAttributeName:KL_redColor}];
    [topView addSubview:quMoneyLable];
    topView.height = quMoneyLable.bottom + 30;
    __weak typeof(self) weakSelf =  self;
    
    UIView * typeview =  [KLUtils headerViewWithTitle:@"提现账户"];
    typeview.backgroundColor = self.tableView.backgroundColor;
    typeview.top = topView.bottom;
    [header addSubview:typeview];
    
    STButton * typeButton = [[STButton alloc] initWithFrame:CGRectMake(15, typeview.bottom, UIScreenWidth - 30, 44)
                                                      title:@"点击选择提现账户"
                                                 titleColor:KL_firstTextColor
                                                  titleFont:18
                                               cornerRadius:0
                                            backgroundColor:nil
                                            backgroundImage:nil
                                                      image:nil];
    [typeButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedTypeButton];
    }];
    self.typeButton = typeButton;
    [header addSubview:typeButton];
    
    UIView * cardview =  [KLUtils headerViewWithTitle:@"收款银行卡"];
    cardview.backgroundColor = self.tableView.backgroundColor;
    cardview.top = typeButton.bottom;
    [header addSubview:cardview];
    
    
    
    STButton * cardButton = [[STButton alloc] initWithFrame:CGRectMake(15, cardview.bottom, UIScreenWidth - 30, 44)
                                                     title:@"点击选择银行卡"
                                                titleColor:KL_firstTextColor
                                                 titleFont:18
                                              cornerRadius:0
                                           backgroundColor:nil
                                           backgroundImage:nil
                                                     image:nil];
    [cardButton setClicAction:^(UIButton *sender) {
        [weakSelf onSlectedCardButton];
    }];
    self.cardButton = cardButton;
    [header addSubview:cardButton];
    UIView * moneyview =  [KLUtils headerViewWithTitle:@"提现金额"];
     moneyview.backgroundColor = self.tableView.backgroundColor;
    moneyview.top = cardButton.bottom;
    [header addSubview:moneyview];
    
    self.moneyTextFiled = [[UITextField alloc] initWithFrame:CGRectMake(15, moneyview.bottom, UIScreenWidth - 30, 44)];
    self.moneyTextFiled.placeholder = @"单笔提现金额最少30元";
    self.moneyTextFiled.keyboardType = UIKeyboardTypeNumberPad;
    [header addSubview:self.moneyTextFiled];
    
    header.height = self.moneyTextFiled.bottom;
    self.tableView.tableHeaderView = header;
}
- (void)configFooterView{
    __weak typeof(self) weakSelf =  self;
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    footer.backgroundColor = self.tableView.backgroundColor;
    STButton * confimButton = [[STButton alloc] initWithFrame:CGRectMake(30, 0, UIScreenWidth - 60 , 44)
                                                        title:@"确认提现"
                                                   titleColor:[UIColor whiteColor]
                                                    titleFont:18
                                                 cornerRadius:10
                                              backgroundColor:KL_BlueBackGroundColor
                                              backgroundImage:nil
                                                        image:nil];
    [confimButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedCommitButton];
    }];
    confimButton.st_centerY = 50;
    confimButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [footer addSubview:confimButton];
    self.tableView.tableFooterView = footer;
}
- (NSString*)findCidFormBanks{
    NSString * cid;
    for (STBankModel*model in self.dataSouce) {
        if ([model.bank isEqualToString:self.cardButton.currentTitle]) {
            cid = model.bankId.description;
        }
    }
    return cid;
}
#pragma mark --Action Method

- (void)onSlectedCardButton{
    if (!self.dataSouce.count) {
        [SVProgressHUD showErrorWithStatus:@"您还未绑定银行卡，先绑定银行卡"];
        [self.navigationController pushViewController:[STAddCardViewController new] animated:YES];
        return;
    }
    
    NSMutableArray * titleArray = [NSMutableArray new];
    for (STBankModel*model in self.dataSouce) {
        [titleArray addObject:model.bank];
    }
    
    STPickerViewController * vc = [[STPickerViewController alloc] initWithPickerArray:@[titleArray] andWithHandle:^(NSArray<NSString *> *stringArray) {
        NSString * name = stringArray.firstObject;
        [self.cardButton setTitle:name forState:UIControlStateNormal];
        
    }];
    vc.confimTitleColor = KL_BlueBackGroundColor;
    [self presentViewController:vc animated:NO completion:nil];
}
- (void)onSelctedTypeButton{
    STPickerViewController * vc = [[STPickerViewController alloc] initWithPickerArray:@[self.titles] andWithHandle:^(NSArray<NSString *> *stringArray) {
        NSString * name = stringArray.firstObject;
        [self.typeButton setTitle:name forState:UIControlStateNormal];
        
    }];
    vc.confimTitleColor = KL_BlueBackGroundColor;
    [self presentViewController:vc animated:NO completion:nil];
}
- (void)onSelectedCommitButton{
    
    if ([self.typeButton.currentTitle isEqualToString:@"点击选择提现账户"]) {
        [SVProgressHUD showErrorWithStatus:@"您还未选择提现账户"];
        return;
    }
    
    if (!self.dataSouce.count) {
        [SVProgressHUD showErrorWithStatus:@"您还未绑定银行卡，先绑定银行卡"];
        [self.navigationController pushViewController:[STAddCardViewController new] animated:YES];
        return;
    }
    if ([self.cardButton.currentTitle isEqualToString:@"点击选择银行卡"]) {
         [SVProgressHUD showErrorWithStatus:@"您还未选择银行卡"];
        return;
    }
    if (!self.moneyTextFiled.text.length) {
        [SVProgressHUD showErrorWithStatus:@"请输入金额"];
        return;
    }
    [self sendTixianRequest];
}
#pragma mark --NetWork Method
- (void)sendfetchBanksRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/user/bankcard?token=",[STUserManger defult].token];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 [self.tableView.mj_header endRefreshing];
                                                 NSDictionary * dataDic = responseObject[@"data"];
                                                 if ([dataDic.allKeys containsObject:@"list"]) {
                                                     NSArray * dataArray = dataDic[@"list"];
                                                     self.dataSouce = [NSMutableArray new];
                                                     for (NSDictionary* dataDic in dataArray) {
                                                         STBankModel * model = [STBankModel mj_objectWithKeyValues:dataDic];
                                                         [self.dataSouce addObject:model];
                                                     }
                                                 }
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 self.dataSouce = [NSMutableArray new];
                                                 [SVProgressHUD dismiss];
                                                 // [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
- (void)sendTixianRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/user/withdrawals",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    
    NSString * bankID = [self findCidFormBanks];
    if (bankID.length) {
        [dic setObject:bankID forKey:@"bank_id"];
    }
    if (self.moneyTextFiled.text.length) {
         [dic setObject:self.moneyTextFiled.text forKey:@"money"];
    }
    NSInteger index = [self.titles indexOfObject:self.typeButton.currentTitle];
    if (index == 0) {
         [dic setObject:@"0" forKey:@"type"];
    }else{
         [dic setObject:@"1" forKey:@"type"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"已经收到您的提现申请"];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 
                                                 
                                             }];
}
@end
